<template>
  <el-card class="main-container">
    <template #header>
      <div class="card-header">
        <span>路径管理</span>
        <div class="header-operations">
          <!-- 搜索框 -->
          <el-input
            v-model="searchId"
            placeholder="输入路径ID搜索"
            clearable
            @clear="handleSearch"
            @input="handleSearch"
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <!-- 状态筛选 -->
          <el-select 
            v-model="statusFilter" 
            placeholder="状态筛选" 
            clearable 
            @change="handleStatusChange"
            @clear="handleStatusClear"
          >
            <el-option label="运行中" :value="1" />
            <el-option label="已结束" :value="0" />
          </el-select>
          
          <el-button type="primary" @click="handleAdd">
            新增路径
          </el-button>
          <el-button @click="handleSearch" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </template>

    <!-- 路径列表 -->
    <el-table
      :data="routes"
      border
      v-loading="loading"
      style="width: 100%"
    >
      <el-table-column
        prop="routeId"
        label="路径ID"
        width="220"
      />
      <el-table-column
        prop="startPoint"
        label="起点"
        width="180"
      />
      <el-table-column
        prop="endPoint"
        label="终点"
        width="180"
      />
      <el-table-column
        prop="status"
        label="状态"
        width="100"
      >
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '运行中' : '已结束' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="startTime"
        label="开始时间"
        width="180"
      >
        <template #default="{ row }">
          {{ formatDateTime(row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="endTime"
        label="结束时间"
        width="180"
      >
        <template #default="{ row }">
          {{ row.endTime ? formatDateTime(row.endTime) : '-' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="duration"
        label="运行时长"
        width="120"
      >
        <template #default="{ row }">
          {{ formatDuration(row.duration) }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="200"
        fixed="right"
      >
        <template #default="{ row }">
          <el-button
            size="small"
            type="primary"
            :disabled="row.status === 0"
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="warning"
            :disabled="row.status === 0"
            @click="handleFinish(row)"
          >
            结束
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑路径对话框 -->
    <el-dialog
      :title="isEdit ? '编辑路径' : '新增路径'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="路径ID" prop="routeId" v-if="isEdit">
          <el-input v-model="form.routeId" disabled />
        </el-form-item>
        <el-form-item label="自定义ID" prop="routeId" v-else>
          <el-input 
            v-model="form.routeId" 
            placeholder="可选，不填将自动生成"
          />
        </el-form-item>
        <el-form-item label="起点" prop="startPoint">
          <el-input v-model="form.startPoint" placeholder="如：感染性废物暂存区" />
        </el-form-item>
        <el-form-item label="终点" prop="endPoint">
          <el-input v-model="form.endPoint" placeholder="如：高温处理中心" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime" v-if="isEdit && form.status === 0">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted, onActivated } from 'vue'
import { 
  ElMessage, 
  ElMessageBox,
  ElButton,
  ElCard,
  ElTable,
  ElTableColumn,
  ElTag,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElIcon
} from 'element-plus'
import { Refresh, Search } from '@element-plus/icons-vue'
import api from '../api/api'

const routes = ref([])
const dialogVisible = ref(false)
const formRef = ref(null)
const loading = ref(false)
const isEdit = ref(false)
const statusFilter = ref(null)
const searchId = ref('')

const form = reactive({
  routeId: '',
  startPoint: '',
  endPoint: '',
  status: 1,
  endTime: null
})

const rules = {
  startPoint: [
    { required: true, message: '请输入起点', trigger: 'blur' }
  ],
  endPoint: [
    { required: true, message: '请输入终点', trigger: 'blur' }
  ]
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}

// 格式化持续时间
const formatDuration = (seconds) => {
  if (!seconds) {
    // 如果没有 seconds，说明是运行中的路径，需要实时计算
    return '-'
  }
  
  // 确保 seconds 是正数
  const duration = Math.abs(seconds)
  const hours = Math.floor(duration / 3600)
  const minutes = Math.floor((duration % 3600) / 60)
  const remainingSeconds = duration % 60
  return `${hours}时${minutes}分${remainingSeconds}秒`
}

// 获取路径列表
const fetchRoutes = async () => {
  loading.value = true
  try {
    let response
    
    // 如果有输入ID，优先使用ID查询
    if (searchId.value.trim()) {
      response = await api.getRouteDetail(searchId.value.trim())
      // 如果是查询单个路径，需要将返回的对象包装成数组
      routes.value = response.data ? [response.data] : []
      loading.value = false
      return
    }
    
    // 否则使用列表查询
    if (statusFilter.value === 0 || statusFilter.value === 1) {  // 明确检查状态值
      // 有状态筛选时，添加状态参数
      response = await api.getRoutes(`/routes?status=${statusFilter.value}`)
    } else {
      // 没有状态筛选时，获取所有路径
      response = await api.getRoutes('/routes')  // 直接使用基础路径
    }
    
    routes.value = response.data || []  // 确保返回空数组而不是 null
  } catch (error) {
    if (error.response?.status === 404) {
      routes.value = [] // 找不到路径时显示空列表
      ElMessage.warning('未找到相关路径')
    } else {
      ElMessage.error('获取路径列表失败')
    }
  } finally {
    loading.value = false
  }
}

// 新增路径
const handleAdd = () => {
  isEdit.value = false
  form.routeId = ''
  form.startPoint = ''
  form.endPoint = ''
  form.status = 1
  form.endTime = null
  dialogVisible.value = true
}

// 编辑路径
const handleEdit = async (row) => {
  try {
    const response = await api.getRouteDetail(row.routeId)
    Object.assign(form, response.data)
    isEdit.value = true
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取路径详情失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    if (isEdit.value) {
      await api.updateRoute(form.routeId, form)
      ElMessage.success('更新成功')
    } else {
      await api.createRoute(form)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    await fetchRoutes()
  } catch (error) {
    ElMessage.error(error?.message || (isEdit.value ? '更新失败' : '创建失败'))
  }
}

// 结束路径
const handleFinish = async (row) => {
  try {
    await ElMessageBox.confirm('确认要结束该路径吗？', '提示', {
      type: 'warning'
    })
    
    // 获取当前北京时间
    const now = new Date()
    // 转换为 ISO 字符串时会自动使用 UTC，所以需要加上时区偏移
    const endTime = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString()
    const startTime = new Date(row.startTime)
    const endTimeDate = new Date(endTime)
    
    // 计算运行时长（秒），确保是正数
    const duration = Math.abs(Math.floor((endTimeDate - startTime) / 1000))
    
    // 发送更新请求时需要保留原有数据，更新状态、结束时间和运行时长
    await api.updateRoute(row.routeId, {
      ...row,
      status: 0,
      endTime: endTime,
      duration: duration
    })
    
    ElMessage.success('操作成功')
    await fetchRoutes()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('结束路径失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 删除路径
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认要删除该路径吗？', '提示', {
      type: 'warning'
    })
    await api.deleteRoute(row.routeId)
    ElMessage.success('删除成功')
    await fetchRoutes()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 处理搜索
const handleSearch = () => {
  fetchRoutes()
}

// 处理状态筛选清除
const handleStatusClear = async () => {
  statusFilter.value = null
  await fetchRoutes()  // 等待获取最新数据
}

// 处理状态筛选变化
const handleStatusChange = async () => {
  await fetchRoutes()  // 等待获取最新数据
}

onActivated(() => {
  fetchRoutes()
})
</script>

<style scoped>
.main-container {
  margin: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-operations {
  display: flex;
  gap: 12px;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-table) {
  margin-top: 16px;
}

.search-input {
  width: 200px;
}

:deep(.el-select) {
  width: 120px;
}
</style> 